using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Localization;
using Microsoft.VisualBasic;

namespace Code5Systems.FormMaster
{

	public partial class Render : System.Web.UI.Page
	{
		
#region  Web Form Designer Generated Code
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		protected System.Web.UI.WebControls.HyperLink hlClose;
		protected System.Web.UI.WebControls.Label lblNotAuthorized;
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
			//Thread.CurrentThread.CurrentUICulture = New CultureInfo("he-IL")
		}
		
#endregion
		
		
#region Private Members
		
		private int _portalID = -1;
		private int _tabId = -1;
		private int _moduleID = -1;
		private int _fileDataId = -1;
		private bool bAuthorized = false;
		private Code5Systems.FormMaster.Business.FormFileDataInfo objFileDataInfo;
		private Code5Systems.FormMaster.Business.FormFileDataController objFileCtl;
#endregion
		
		
#region Event Handlers
		
		private void Page_Load(System.Object sender, System.EventArgs e)
		{
			
			if (Information.IsNumeric(Request.Params["FileDataId"]))
			{
				_fileDataId = System.Convert.ToInt32(Request.Params["FileDataId"]);
			}
			
			this.lblNotAuthorized.Visible = false;
			
			objFileCtl = new Code5Systems.FormMaster.Business.FormFileDataController();
			objFileDataInfo = objFileCtl.Get(_fileDataId);
			
			if (objFileDataInfo != null)
			{
				_portalID = objFileDataInfo.PortalId;
				_tabId = objFileDataInfo.TabId;
				_moduleID = objFileDataInfo.ModuleId;
				
				FormSettings objFormSettings = Utility.GetFormSettings(_moduleID);
				
				if (objFormSettings.AuthFileDownloads)
				{
					
					//Verify that the user is allowed to accesss this page since
					//we are out of the scope of the DNN Security system
					UserInfo objUser = default(UserInfo);
					
					UserController objUserCtl = new UserController();
					if (Context.User.Identity.IsAuthenticated)
					{
						ModuleController objModuleController = new ModuleController();
						ModuleInfo objModuleInfo = objModuleController.GetModule(_moduleID, _tabId);
						
						objUser = UserController.GetUserByName(_portalID, Context.User.Identity.Name);
						if (objUser.IsSuperUser || objUser.IsInRole("Administrators"))
						{
							bAuthorized = true;
						}
						else
						{
							int iIndex = default(int);
							ModulePermissionCollection permissions = ModulePermissionController.GetModulePermissions(_moduleID, _tabId);
							
							List<string> editRoles = new List<string>();
							
							foreach (ModulePermissionInfo permission in permissions)
							{
								if (permission.AllowAccess)
								{
									if (permission.PermissionKey == "EDIT")
									{
										if (permission.UserID == objUser.UserID)
										{
											bAuthorized = true;
											break;
										}
										editRoles.Add(permission.RoleName);
									}
								}
							}
							
							if (!bAuthorized)
							{
								DotNetNuke.Security.Roles.RoleController objRoleController = new DotNetNuke.Security.Roles.RoleController();
								
								string[] aryUserRoles = objRoleController.GetRolesByUser(objUser.UserID, _portalID);
								
								if (aryUserRoles != null)
								{
									for (iIndex = 0; iIndex <= aryUserRoles.Length - 1; iIndex++)
									{
										if (editRoles.Contains(aryUserRoles[iIndex]))
										{
											bAuthorized = true;
											break;
										}
									}
								}
							}
						}
						
					}
				}
				else
				{
					bAuthorized = true;
				}
			}
		}

		public override void RenderControl(HtmlTextWriter writer)
		{
			
			if (bAuthorized)
			{
				string strErrMsg = Localization.GetString("Download.ErrorMessage", objFileCtl.SharedResouceFile);
				
				try
				{
					if (!objFileDataInfo.InDB)
					{
						FileStream MyFileStream = default(FileStream);
						
						MyFileStream = new FileStream(Server.MapPath(objFileDataInfo.FullFilePath), FileMode.Open);
						objFileDataInfo.FileData = new byte[objFileDataInfo.ContentLegth - 1 + 1];
						
						MyFileStream.Read(objFileDataInfo.FileData, 0, objFileDataInfo.ContentLegth);
						MyFileStream.Close();
					}
					
					//Dim dbStream As Stream = Nothing
					//dbStream = New MemoryStream(objFileDataInfo.FileData)
					//Dim objBinaryReader As BinaryReader = New BinaryReader(dbStream)
					//objFileDataInfo.FileData = Nothing
					//GC.Collect()
					//objFileDataInfo.FileData = objBinaryReader.ReadBytes(CType(dbStream.Length, Integer))
					
					Response.ContentType = objFileDataInfo.ContentType;
					
					Response.AddHeader("Content-Disposition", "attachment;filename=" + objFileDataInfo.OrigFileName.Replace(" ", "-"));
					
					Response.BinaryWrite(objFileDataInfo.FileData);
					
				}
				catch (IOException ioEx)
				{
					Response.Write(strErrMsg.Replace("[EXCEPTION]", ioEx.Message));
				}
				catch (Exception ex)
				{
					Response.Write(strErrMsg.Replace("[EXCEPTION]", ex.Message));
				}
				
			}
			else
			{
				this.lblNotAuthorized.Visible = true;
				this.lblNotAuthorized.Text = Localization.GetString("AccessDenied", objFileCtl.SharedResouceFile);
				base.Render(writer);
			}
			
		}

#endregion
		
		
#region Helper Methods
		
		
		
#endregion
		
		
	}
	
}

